﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace CommonMethod
{
    public static class ExcelHelper
    {
        /// <summary>
        /// List导出到EXCEL
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objList"></param>
        /// <param name="FilePath"></param>
        /// <param name="columnInfo"></param>
        /// <returns></returns>
        public static void ListToExcel<T>(List<T> objList, string FilePath, string[] columnInfo)
        {
            var type = typeof(T);
            PropertyInfo[] props = type.GetProperties();
            IWorkbook workbook = new HSSFWorkbook();
           //创建工作表
            ISheet sheet = workbook.CreateSheet("sheet");
            IRow row0 = sheet.CreateRow(0);
            for (int i = 0; i < columnInfo.Count(); i++)
            {
                row0.CreateCell(i).SetCellValue(columnInfo[i]);
            }

            for (int r = 1; r <= objList.Count; r++)
            {
            //创建行row
                IRow row = sheet.CreateRow(r);
                for (int j = 0; j < props.Count(); j++)
                {
                    row.CreateCell(j).SetCellValue(props[j].GetValue(objList[r-1]).ToString());
                }
            }
            File.Delete(FilePath);
            //创建流对象并设置存储Excel文件的路径
            using (FileStream url = File.OpenWrite(FilePath))
            {
                //导出Excel文件
                workbook.Write(url);
            };
        }

    }
}
